package model;

import connection.DbConnection;
import java.sql.*;

public class CAIImpl{
	static DbConnection conn = new DbConnection();
	
	/**
	 * Returns the status int on Question.
	 * */
	public int getState(int qID){
		try{
			conn.close();
		}catch(Exception e){
			System.out.println("error closing conn in doPost of caiservlet");
		}
		conn = new DbConnection();
		
		int status=-1;
		PreparedStatement ps;
		try{
			String sql = "SELECT status FROM Question WHERE QuestionID="+qID;
			ps = conn.getConn().prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				System.out.println("here2");
				status = rs.getInt(1);
				System.out.println(status);
			}
			ps.close();
		}catch(Exception e){
			System.out.println("Error in setQuestionState! [getting status]");
			e.printStackTrace();
		}
		return status;
	}
	
	/**
	 * Toggles the status int on Question.
	 * */
	public void toggleState(int qID, String status){
		try{
			conn.close();
		}catch(Exception e){
			System.out.println("error closing conn in doPost of caiservlet");
		}
		conn = new DbConnection();
		
		String sql = "UPDATE Question SET status = ";
		System.out.println("toggling question");
		if(status == "0"){
			sql += "1";
		}else{
			sql += "0";
		}
		sql += " WHERE QuestionID = "+qID;
		System.out.println(sql);
		PreparedStatement ps;
		try{
			ps = conn.getConn().prepareStatement(sql);
			ps.executeQuery();
		}catch(Exception e){
			System.out.println("Error in setQuestionState! [setting status]");
			e.printStackTrace();
		}
	}
	
	public boolean getCorrect(int qID, String op){
		try{
			conn.close();
		}catch(Exception e){
			System.out.println("error closing conn in doPost of caiservlet");
		}
		conn = new DbConnection();
		String sql = "SELECT CorrectChoice FROM Options WHERE CorrectChoice='y' AND OptionID="+op+" AND QuestionID="+qID;
		System.out.println(sql);
		
		try{
			PreparedStatement ps = conn.getConn().prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				return true;
			}else{
				return false;
			}
		}catch(SQLException e){
			System.out.println("Exception in getCorrect");
		}
		return false;
	}
}